package org.jiucheng.magpiebridge.manager.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jiucheng.magpiebridge.manager.out.TplOut;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.RequestMethod;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

/**
 * @see com.google.code.kaptcha.servlet.KaptchaServlet
 * @author jiucheng
 *
 */
@Controller
public class KaptchaController {
    
    private Producer kaptchaProducer = null;
    // private String sessionKeyValue = null;
    // private String sessionKeyDateValue = null;
    
    public KaptchaController() {
        ImageIO.setUseCache(false);
        Properties props = new Properties();
        props.setProperty("kaptcha.border", "no");
        props.setProperty("kaptcha.textproducer.char.string", "ACDEFHKPRSTWX345679");
        Config config = new Config(props);
        this.kaptchaProducer = config.getProducerImpl();
        // this.sessionKeyValue = config.getSessionKey();
        // this.sessionKeyDateValue = config.getSessionDate();
    }
    
    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET, out = TplOut.class)
    public void kaptcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Set to expire far in the past.
        resp.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        resp.setHeader("Pragma", "no-cache");

        // return a jpeg
        resp.setContentType("image/jpeg");

        // create the text for the image
        String capText = this.kaptchaProducer.createText();

        // store the text in the session
        // req.getSession().setAttribute(this.sessionKeyValue, capText);

        // store the date in the session so that it can be compared
        // against to make sure someone hasn't taken too long to enter
        // their kaptcha
        // req.getSession().setAttribute(this.sessionKeyDateValue, new Date());
        
        Cookie cookie = new Cookie("kaptcha", capText);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        resp.addCookie(cookie);

        // create the image with the text
        BufferedImage bi = this.kaptchaProducer.createImage(capText);
        ServletOutputStream out = resp.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        out.close();
    }
}
